local sk__jiyin = fk.CreateSkill {

  name = "sk__jiyin",

  tags = { Skill.Compulsory, },

}

sk__jiyin:addAcquireEffect(function(self, player, is_start)
  player.room:addPlayerMark(player, "@sk__jiyin", 3)
end)

sk__jiyin:addLoseEffect(function(self, player)
  local n = player:getMark("@sk__jiyin")
  player.room:setPlayerMark(player, "@sk__jiyin", 0)
  if n > 0 then
    local cards = player.room:getCardsFromPileByRule(".|.|spade,club", n, "drawPile")
    if #cards > 0 then
      player.room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonDraw, sk__jiyin.name, nil, false, player)
    end
  end
end)

sk__jiyin:addEffect(fk.AfterCardsMove, {
  anim_type = "offensive",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(sk__jiyin.name) and player:getMark("@sk__jiyin") > 0 then
      for _, move in ipairs(data) do
        if move.from == player then
          for _, info in ipairs(move.moveInfo) do
            if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and
                Fk:getCardById(info.cardId).color == Card.Black then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = 0
    for _, move in ipairs(data) do
      if move.from == player then
        for _, info in ipairs(move.moveInfo) do
          if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and
              Fk:getCardById(info.cardId).color == Card.Black then
            n = n + 1
          end
        end
      end
    end
    for i = 1, n, 1 do
      if player.dead or player:getMark("@sk__jiyin") == 0 then return end
      local to = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1,
        "#sk__jiyin-choose", sk__jiyin.name, true)
      if #to > 0 then
        room:removePlayerMark(player, "@sk__jiyin", 1)
        to = room:getPlayerById(to[1])
        if to:isWounded() then
          room:changeMaxHp(to, -1)
        else
          room:damage {
            from = player,
            to = to,
            damage = 1,
            damageType = fk.ThunderDamage,
            skillName = sk__jiyin.name,
          }
        end
      else
        return
      end
    end
  end,
})


return sk__jiyin
